
import 'dart:async';
import 'dart:convert';

import 'package:flutter/services.dart';

class FlutterMixPush {
  static const String ON_REGISTER_SUCCEED = "onRegisterSucceed";
  static const String ON_NOTIFY_MSG_CLICKED = "onNotifyMsgClicked";

  static FlutterMixPush? _instance;
  static const MethodChannel _channel = MethodChannel('flutter_mix_push');
  Map<String, List> _listener = {};

  static FlutterMixPush get instance {
    _instance ??= FlutterMixPush._private();
    return _instance!;
  }

  FlutterMixPush._private() {
    _channel.setMethodCallHandler(_handleMessages);
  }

  /// 回调
  Future<void> _handleMessages(MethodCall call) async {
    switch (call.method) {
      case ON_REGISTER_SUCCEED:
        if (_listener[call.method] is List) {
          _listener[call.method]?.forEach((item) {
            item(MixPushPlatform.fromJson(call.arguments));
          });
        }
        break;
      case ON_REGISTER_SUCCEED:
        if (_listener[call.method] is List) {
          _listener[call.method]?.forEach((item) {
            item(MixPushMessage.fromJson(call.arguments));
          });
        }
        break;
    }
  }

  addListener(String key, dynamic fuction) {
    _listener.putIfAbsent(key, () => []);
    _listener[key]?.add(fuction);
  }

  /// 调用
  static Future<String?> get platformVersion async {
    final String? version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  static Future<bool?> doRegister() async {
    final bool? succ = await _channel.invokeMethod('doRegister');
    return succ;
  }
}

class MixPushPlatform {
  String? platformName;
  String? regId;

  MixPushPlatform.fromJson(String json) {
    var map = jsonDecode(json);
    platformName = map["platformName"];
    regId = map["regId"];
  }
}

class MixPushMessage {
  String? title;
  String? description;
  String? platform;
  String? payload;
  bool? passThrough;

  MixPushMessage.fromJson(String json) {
    var map = jsonDecode(json);
    title = map["title"];
    description = map["description"];
    platform = map["platform"];
    payload = map["payload"];
    passThrough = map["passThrough"] == "1";
  }
}

